#!/usr/bin/python3
# -*- coding: utf-8 -*-

import json
import logging
import aiohttp
import aiohttp_jinja2
from aiohttp import web

import db
from coreweb import query_string, post_params


def create_datars_middleware():
    @web.middleware
    async def datars_middleware(request, handler):
        response = await handler(request)
        datars = None
        params = {}
        try:
            if request.method == 'GET':
                params = query_string(request)
            elif request.method == 'POST':
                params = await post_params(request)
            if isinstance(response, dict):
                snd = response
                if response.get('__template__', None):
                    response = web.Response(body=request.app['__templating__'].get_template(
                        response.get('__template__')).render(**response['data']).encode('utf-8'))
                    response.content_type = 'text/html;charset=utf-8'
                else:
                    response = web.Response(body=json.dumps(
                        response, default=lambda obj: obj.__dict__).encode('utf-8'))
                    response.content_type = 'application/json;charset=utf-8'
                datars = db.Datars(method=request.method, path=request.path, handler=handler.__name__, module='', rcv=str(params), snd=str(
                    snd), content_type=response.content_type if hasattr(response, 'content_type') else None, response_type=str(type(response)))
            elif isinstance(response, aiohttp.web_response.Response):
                resp = None
                if hasattr(response, 'content_type'):
                    if response.content_type == 'application/json':
                        resp = json.dumps(json.loads(
                            response.body), ensure_ascii=False)
                datars = db.Datars(method=request.method, path=request.path, handler=handler.__name__, module='', rcv=str(params), snd=str(
                    resp), content_type=response.content_type if hasattr(response, 'content_type') else None, response_type=str(type(response)))
            if datars:
                logging.info('-' * 65)
                logging.info('datars: %s' % datars)
                logging.info('-' * 65)
                session = db.create_session()
                session.add(datars)
                session.commit()
        except BaseException as e:
            logging.error('[ERROR] datars: %s' % e)
        return response
    return datars_middleware


def setup_middlewares(app):
    datars_middleware = create_datars_middleware()
    app.middlewares.append(datars_middleware)
